/**
 * interactionService.js
 * 提供医学影像查看器的交互功能
 * 从ViewerPage.vue中提取，负责处理鼠标和键盘交互相关的功能
 */

import cornerstone from 'cornerstone-core';
import * as cornerstoneService from './cornerstoneService';

// 保存滚动方向检测的上一个索引
let _lastIndex = null;

/**
 * 处理键盘快捷键
 * @param {KeyboardEvent} event - 键盘事件
 * @param {HTMLElement} element - 视口元素
 * @param {Object} callbacks - 回调函数对象
 * @returns {void}
 */
export function handleKeyDown(event, element, callbacks) {
  // 处理键盘快捷键
  switch (event.key) {
    case 'ArrowLeft':
      if (callbacks.previousImage) {
        callbacks.previousImage();
        event.preventDefault();
      }
      break;
    case 'ArrowRight':
      if (callbacks.nextImage) {
        callbacks.nextImage();
        event.preventDefault();
      }
      break;
    case 'ArrowUp':
      if (callbacks.adjustWindowLevel) {
        callbacks.adjustWindowLevel(0, 10);  // 增加窗位
        event.preventDefault();
      }
      break;
    case 'ArrowDown':
      if (callbacks.adjustWindowLevel) {
        callbacks.adjustWindowLevel(0, -10);  // 减少窗位
        event.preventDefault();
      }
      break;
    case '+':
    case '=':
      if (callbacks.adjustWindowLevel) {
        callbacks.adjustWindowLevel(10, 0);  // 增加窗宽
        event.preventDefault();
      }
      break;
    case '-':
      if (callbacks.adjustWindowLevel) {
        callbacks.adjustWindowLevel(-10, 0);  // 减少窗宽
        event.preventDefault();
      }
      break;
    case 'r':
    case 'R':
      if (callbacks.resetView) {
        callbacks.resetView();  // 重置视图
        event.preventDefault();
      }
      break;
    case 'f':
    case 'F':
      if (callbacks.toggleFullscreen) {
        callbacks.toggleFullscreen();  // 全屏
        event.preventDefault();
      }
      break;
  }
}

/**
 * 设置键盘快捷键
 * @param {Function} handler - 键盘事件处理函数
 * @returns {Function} 移除事件监听的函数
 */
export function setupKeyboardShortcuts(handler) {
  // 添加键盘快捷键
  document.addEventListener('keydown', handler);
  
  // 返回一个函数用于移除事件监听
  return () => document.removeEventListener('keydown', handler);
}

/**
 * 处理全屏变化
 * @param {Function} callback - 全屏状态变化的回调函数
 * @returns {Function} 移除事件监听的函数
 */
export function setupFullscreenListeners(callback) {
  const handleFullscreenChange = () => {
    // 检测当前是否处于全屏状态
    const isFullscreen = !!(
      document.fullscreenElement ||
      document.webkitFullscreenElement ||
      document.mozFullScreenElement ||
      document.msFullscreenElement
    );
    
    if (callback) {
      callback(isFullscreen);
    }
  };
  
  // 监听全屏变化
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.addEventListener('mozfullscreenchange', handleFullscreenChange);
  document.addEventListener('MSFullscreenChange', handleFullscreenChange);
  
  // 返回一个函数用于移除事件监听
  return () => {
    document.removeEventListener('fullscreenchange', handleFullscreenChange);
    document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
    document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
    document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
  };
}

/**
 * 切换全屏显示
 * @param {HTMLElement} element - 要全屏显示的元素
 * @param {boolean} isFullscreen - 当前是否已全屏
 * @returns {boolean} 切换成功返回true，失败返回false
 */
export function toggleFullscreen(element, isFullscreen) {
  try {
    if (!isFullscreen) {
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
      } else {
        return false;
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      } else {
        return false;
      }
    }
    return true;
  } catch (error) {
    console.error('切换全屏失败:', error);
    return false;
  }
}

/**
 * 设置鼠标事件监听
 * @param {HTMLElement} element - 视口元素
 * @param {Object} handlers - 事件处理函数对象
 * @returns {Function} 移除事件监听的函数
 */
export function setupMouseEvents(element, handlers) {
  if (!element) {
    return () => {};
  }
  
  if (handlers.mouseDown) element.addEventListener('mousedown', handlers.mouseDown);
  if (handlers.mouseUp) element.addEventListener('mouseup', handlers.mouseUp);
  if (handlers.mouseMove) element.addEventListener('mousemove', handlers.mouseMove);
  if (handlers.mouseLeave) element.addEventListener('mouseleave', handlers.mouseLeave);
  if (handlers.mouseWheel) element.addEventListener('wheel', handlers.mouseWheel);
  
  // 返回一个函数用于移除事件监听
  return () => {
    if (handlers.mouseDown) element.removeEventListener('mousedown', handlers.mouseDown);
    if (handlers.mouseUp) element.removeEventListener('mouseup', handlers.mouseUp);
    if (handlers.mouseMove) element.removeEventListener('mousemove', handlers.mouseMove);
    if (handlers.mouseLeave) element.removeEventListener('mouseleave', handlers.mouseLeave);
    if (handlers.mouseWheel) element.removeEventListener('wheel', handlers.mouseWheel);
  };
}

/**
 * 设置全局鼠标事件监听
 * @param {Object} handlers - 事件处理函数对象
 * @returns {Function} 移除事件监听的函数
 */
export function setupGlobalMouseEvents(handlers) {
  if (handlers.mouseDown) document.addEventListener('mousedown', handlers.mouseDown);
  if (handlers.mouseUp) document.addEventListener('mouseup', handlers.mouseUp);
  if (handlers.mouseMove) document.addEventListener('mousemove', handlers.mouseMove);
  
  // 返回一个函数用于移除事件监听
  return () => {
    if (handlers.mouseDown) document.removeEventListener('mousedown', handlers.mouseDown);
    if (handlers.mouseUp) document.removeEventListener('mouseup', handlers.mouseUp);
    if (handlers.mouseMove) document.removeEventListener('mousemove', handlers.mouseMove);
  };
}

/**
 * 处理鼠标滚轮事件
 * @param {WheelEvent} event - 滚轮事件
 * @param {number} currentIndex - 当前图像索引
 * @param {number} totalImages - 总图像数量
 * @param {Function} displayImageCallback - 显示图像的回调函数
 * @returns {boolean} 成功返回true，失败返回false
 */
export function handleMouseWheel(event, currentIndex, totalImages, displayImageCallback) {
  event.preventDefault();
  
  if (totalImages <= 1) return false;
  
  // 确定滚动方向
  const direction = event.deltaY > 0 ? 1 : -1;
  
  // 计算新的索引
  let newIndex = currentIndex + direction;
  
  // 确保索引在有效范围内
  newIndex = Math.max(0, Math.min(totalImages - 1, newIndex));
  
  // 如果索引变化，显示新图像
  if (newIndex !== currentIndex && displayImageCallback) {
    displayImageCallback(newIndex);
    return true;
  }
  
  return false;
}

/**
 * 创建防抖函数
 * @param {Function} func - 要执行的函数
 * @param {number} wait - 等待时间（毫秒）
 * @returns {Function} 防抖函数
 */
export function debounce(func, wait) {
  let timeout;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

/**
 * 创建节流函数
 * @param {Function} func - 要执行的函数
 * @param {number} limit - 限制时间（毫秒）
 * @returns {Function} 节流函数
 */
export function throttle(func, limit) {
  let inThrottle;
  return function() {
    const context = this;
    const args = arguments;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

/**
 * 滚动到指定图像
 * @param {number} startIndex - 起始图像索引
 * @param {number} delta - 滚动距离
 * @param {number} totalImages - 总图像数量
 * @param {number} sensitivity - 灵敏度
 * @returns {number} 目标图像索引
 */
export function calculateScrollTarget(startIndex, delta, totalImages, sensitivity = 2) {
  const scrollAmount = Math.round(delta * sensitivity);
  
  if (scrollAmount === 0) {
    return startIndex;
  }
  
  return Math.max(0, Math.min(totalImages - 1, startIndex + scrollAmount));
}

/**
 * 检测滚动方向
 * @param {number} currentIndex - 当前图像索引
 * @returns {number} 方向值，正数表示向前，负数表示向后
 */
export function detectScrollDirection(currentIndex) {
  // 简单的方向检测
  if (_lastIndex === null) {
    _lastIndex = currentIndex;
    return 1; // 默认向前
  }
  
  const direction = currentIndex - _lastIndex;
  _lastIndex = currentIndex;
  return direction;
}

/**
 * 重置滚动方向检测
 */
export function resetScrollDirection() {
  _lastIndex = null;
}

/**
 * 格式化日期
 * @param {string} dateStr - 日期字符串（格式: YYYYMMDD）
 * @returns {string} 格式化后的日期（格式: YYYY-MM-DD）
 */
export function formatDate(dateStr) {
  if (!dateStr || dateStr === 'Unknown') return '';
  
  // 格式化日期，例如从 "19800101" 转换为 "1980-01-01"
  if (dateStr.length === 8) {
    return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
  }
  
  return dateStr;
}

/**
 * 格式化研究日期
 * @param {string} dateStr - 日期字符串（格式: YYYYMMDD）
 * @returns {string} 格式化后的日期（格式: YYYY-MM-DD）
 */
export function formatStudyDate(dateStr) {
  if (!dateStr || dateStr === 'Unknown') return '未知日期';
  
  // 格式化日期，例如从 "20230101" 转换为 "2023-01-01"
  if (dateStr.length === 8) {
    return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
  }
  
  return dateStr;
} 